package com.googlecode.xapper;

import java.util.LinkedList;
import java.util.List;

import nu.xom.*;

public class HtmlQuery {

	private static final String XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml";

	private final static XPathContext XHTML_XPATH_CONTEXT = new XPathContext("html", XHTML_NAMESPACE);

	public List<Element> findElementsMatching(String xpathQuery) {
		List<Element> elements = new LinkedList<Element>();
		
		Nodes nodes = queryElement.query(xpathQuery, XHTML_XPATH_CONTEXT);
		
		for (int i = 0; i < nodes.size(); i++) {
			Node node = nodes.get(i);
			
			if(node instanceof Element) {
				elements.add((Element) node);
			}
		}
		
		return elements;
	}
	
	public static final HtmlQuery query(Element aRootElement) {
		return new HtmlQuery(aRootElement);
	}
	
	public static final HtmlQuery query(Document aDocument) {
		return HtmlQuery.query(aDocument.getRootElement());
	}
	
	private final Element queryElement;
	
	private HtmlQuery(Element anElement) {
		queryElement = anElement;
	}
}
